const addButton = document.querySelector('.add')
const chatList = document.querySelector('.chat_item')

const newChat = async () => {
    // 从后端获取新的chatId
    const response = await fetch('/generate_chat_id');

    const data = await response.json();
    const chatId = data.chatId;


    // 为每个新增li添加点击事件
    const newItem = document.createElement('li');
    newItem.className = 'item';
    newItem.id = chatId;

    newItem.addEventListener('click', () => {
        const li = event.target.closest('li');
        if (li) {
            // 先切换到对话界面
            showContent('chat');
            
            const a = li.querySelector('a');
            document.querySelectorAll('.link.active').forEach(link => {
                link.classList.remove('active');
            });
            a.classList.add('active');
            clearAdditionalMessages();
            loadConversationHistory(li.id)
            sendCurrentChatId(li.id);
        }
    });

    const link = document.createElement('a');
    link.className = 'link flex';
    link.href = '#';

    const icon = document.createElement('i');
    icon.className = 'bx bxs-message';
    const editIcon = document.createElement('i');
    editIcon.className = 'bx bxs-edit-alt';
    editIcon.style.cssText = 'position: absolute; width: 25px; height: 25px; right: 40px';
    editIcon.addEventListener('click', () => {
        const chatName = event.target.previousElementSibling;
        if(chatName) chatName.innerHTML = `<input type="text" id="userInput" maxlength="12" placeholder="Enter a name" style="width: 110px; border-radius: 10px" >`;
        const input = document.querySelector("#userInput");
        input.addEventListener('click', () => {
            event.stopPropagation(); // 阻止事件冒泡
        });
        input.addEventListener('keydown', () => {
            // 检查按下的键是否是Enter键
            if (event.key === 'Enter') {
                const chatName = event.target.closest('span');
                chatName.innerHTML = input.value;
                sendChatDataToBackend(newItem.id,input.value)
            }
        });
        event.stopPropagation(); // 阻止事件冒泡
    });

    const trashIcon = document.createElement('i');
    trashIcon.className = 'bx bxs-trash';
    trashIcon.style.cssText = 'position: absolute; width: 25px; height: 25px; right: 10px';
    trashIcon.addEventListener('click', () => {
        const item = event.target.closest('.item');
        if (item) item.remove();
        sendDeleteDateToBack(item.id);
        event.stopPropagation(); // 阻止事件冒泡
        if(document.querySelectorAll('.link.active').length === 0) {
            if(chatList.firstChild.id) {
                chatList.firstChild.click();
            }
        }
    });

    const span = document.createElement('span');
    span.textContent = '新对话 ' + chatId.slice(5);

    link.appendChild(icon);
    link.appendChild(span);
    link.appendChild(editIcon);
    link.appendChild(trashIcon);
    newItem.appendChild(link);

    // 添加到ul内最上方
    if (chatList.firstChild) {
        chatList.insertBefore(newItem, chatList.firstChild);
    } else {
        chatList.appendChild(newItem);
    }

    sendChatDataToBackend(chatId, span.textContent);
    newItem.click();
}
addButton.addEventListener('click', newChat)

// Function to send data to the backend
const sendChatDataToBackend = (chatId, chatText) => {
    fetch('/save_chat_info', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            chatId: chatId,
            chatText: chatText
        })
    })
        .then(response => response.json())
        .then(data => {
            console.log('Success:', data);
        })
        .catch((error) => {
            console.error('Error:', error);
        });
};

const sendDeleteDateToBack = async (chatId) => {
    console.log("delete")
    await fetch('/delete_chat_info', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            chatId: chatId
        })
    })
        .then(response => response.json())
        .then(data => {
            console.log('Success:', data);
            // 在后端成功删除聊天信息后，再删除前端显示
            const item = document.getElementById(chatId);
            if (item) {
                item.remove();
            }

            if (chatList.children.length === 0) {
                newChat();
            }

            // 然后触发点击事件，以便更新对话框
            if (document.querySelectorAll('.link.active').length === 0) {
                if(chatList.firstChild.id) {
                    chatList.firstChild.click();
                }
            }
        })
        .catch((error) => {
            console.error('Error:', error);
        });
};


const loadChat = (chatId, chatText) => {
    // 为每个新增li添加点击事件
    const newItem = document.createElement('li');
    newItem.className = 'item';
    newItem.id = chatId; // 使用 chatId 变量作为id

    newItem.addEventListener('click', (event) => {
        const li = event.target.closest('li');
        if (li) {
            const a = li.querySelector('a');
            document.querySelectorAll('.link.active').forEach(link => {
                link.classList.remove('active');
            });
            a.classList.add('active');
            clearAdditionalMessages();
            loadConversationHistory(li.id);
            sendCurrentChatId(li.id);
        }
    });

    const link = document.createElement('a');
    link.className = 'link flex';
    link.href = '#';

    const icon = document.createElement('i');
    icon.className = 'bx bxs-message';
    const editIcon = document.createElement('i');
    editIcon.className = 'bx bxs-edit-alt';
    editIcon.style.cssText = 'position: absolute; width: 25px; height: 25px; right: 40px';
    editIcon.addEventListener('click', (event) => {
        event.stopPropagation(); // 阻止事件冒泡
        const chatName = event.target.previousElementSibling;
        if (chatName) {
            chatName.innerHTML = `<input type="text" id="userInput" maxlength="12" placeholder="Enter a name" style="width: 110px; border-radius: 10px" >`;
            const input = document.querySelector("#userInput");
            input.addEventListener('click', (event) => {
                event.stopPropagation(); // 阻止事件冒泡
            });
            input.addEventListener('keydown', (event) => {
                event.stopPropagation(); // 阻止事件冒泡
                // 检查按下的键是否是Enter键
                if (event.key === 'Enter') {
                    const chatName = event.target.closest('span');
                    chatName.innerHTML = input.value;
                    sendChatDataToBackend(chatId, input.value);
                }
            });
        }
    });

    const trashIcon = document.createElement('i');
    trashIcon.className = 'bx bxs-trash';
    trashIcon.style.cssText = 'position: absolute; width: 25px; height: 25px; right: 10px';
    trashIcon.addEventListener('click', (event) => {
        event.stopPropagation(); // 阻止事件冒泡
        const item = event.target.closest('.item');
        sendDeleteDateToBack(item.id);
        if (item) item.remove();
        if (document.querySelectorAll('.link.active').length === 0) {
            if(chatList.firstChild.id) {
                chatList.firstChild.click();
            }
        }
    });

    const span = document.createElement('span');
    span.textContent = chatText;

    link.appendChild(icon);
    link.appendChild(span);
    link.appendChild(editIcon);
    link.appendChild(trashIcon);
    newItem.appendChild(link);

    // 添加到ul内最上方
    if (chatList.firstChild) {
        chatList.insertBefore(newItem, chatList.firstChild);
    } else {
        chatList.appendChild(newItem);
    }

    sendChatDataToBackend(chatId, chatText); 
}

const sendCurrentChatId = (chatId) => {
    fetch('/save_current_chat_id', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            chatId: chatId,
        })
    })
        .then(response => response.json())
        .then(data => {
            console.log('Success:', data);
        })
        .catch((error) => {
            console.error('Error:', error);
        });
};

const clickCurrentChat = () => {
    fetch('/get_current_chat_id')
        .then(response => response.json())
        .then(data => {
            chatId = data['chat_id'];
            const currentChat = document.querySelector(`#${chatId}`);
            if (currentChat) {
                currentChat.click();
            }
        })
        .catch(error => {
            console.error('Error fetching current chat ID:', error);
            if (chatList.firstChild.id) {
                chatList.firstChild.click();
            } else {
                newChat();
            }
        });
}
